package cn.ven.service;

import cn.ven.entity.Blog;
import cn.ven.entity.Like;
import cn.ven.mapper.LikeMapper;
import cn.ven.tool.SessionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired(required = false)
    LikeMapper likeMapper;

    @Autowired
    BlogService blogService;

    @Override
    public int addLike(Like like) {
        LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Like::getBlogid, like.getBlogid());
        queryWrapper.eq(Like::getUid, SessionUtil.getId());
        Like like1 = likeMapper.selectOne(queryWrapper);
        if (like1 == null) {  //判断是否点过赞了，点赞表是否
            like.setUid(SessionUtil.getId());
            likeMapper.insert(like);//插入记录，证明点赞过
            Blog blog = blogService.findById(like.getId());//根据id查找博客
            blog.setLikeNum(blog.getLikeNum()+1);//点赞数+1
            blogService.updateBlog(blog);
            return 1;
        }
        return 0;
    }

    @Override
    public int delLike(int blogid) {
        LambdaQueryWrapper<Like> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Like::getBlogid,blogid);
        queryWrapper.eq(Like::getUid,SessionUtil.getId());
        Like like = likeMapper.selectOne(queryWrapper);
        if (like!=null){
            likeMapper.delete(queryWrapper);//删除点赞记录
            Blog blog = blogService.findById(blogid);//根据博客id查找博客
            blog.setLikeNum(blog.getLikeNum()-1); //点赞数-1
            blogService.updateBlog(blog);
            return 1;
        }
        return 0;
    }

    @Override
    public Like findLike(int blogid) {
        LambdaQueryWrapper<Like> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Like::getBlogid,blogid);
        queryWrapper.eq(Like::getUid,SessionUtil.getId());
        return likeMapper.selectOne(queryWrapper);
    }

}
